package com.at.bilibili.api.aspect;

import com.at.bilibili.api.support.UserSupport;
import com.at.bilibili.domain.UserMoment;
import com.at.bilibili.domain.auth.UserRole;
import com.at.bilibili.domain.constant.AuthRoleConstant;
import com.at.bilibili.domain.exception.ConditionException;
import com.at.bilibili.service.UserRoleService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Aspect // 标记为切面类
@Order(1) // 优先级
@Component
public class DataLimitedAspect {

    @Autowired
    private UserSupport userSupport;
    @Autowired
    private UserRoleService userRoleService;

    // 将切入点 与我们编写的注解进行绑定
    @Pointcut("@annotation(com.at.bilibili.domain.annotation.DataLimited)")
    public void check(){}

    @Before("check()")
    public void doBefore(JoinPoint joinPoint){
        Long userId = userSupport.getCurrentUserId();
        // 获取当前用户的角色
        List<UserRole> userRoleList = userRoleService.getUserRoleByUserId(userId);
        // 获取需要限制的角色编码列表
        Set<String> roleCodeSet = userRoleList.stream().map(UserRole::getRoleCode).collect(Collectors.toSet());
        // 获得连接点传入的参数
        Object[] args = joinPoint.getArgs();
        for(Object arg : args){
            if (arg instanceof UserMoment){
                UserMoment userMoment = (UserMoment)arg;
                String type = userMoment.getType();
                if (roleCodeSet.contains(AuthRoleConstant.ROLE_LV1) && !"0".equals(type)){
                    throw new ConditionException("数据权限不足: 参数异常！！！");
                }
                //TODO
                // type: 0表示视频 1表示直播 2表示专栏动态
                // lv0不支持这个接口 lv1 能0 lv2 能012
            }
        }
    }
}
